package org.jeecgframework.web.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Criteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.system.service.UserService;
import org.jeecgframework.web.util.SendMailUtil;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author  张代浩
 *
 */
@Service("userService")
@Transactional
public class UserServiceImpl extends CommonServiceImpl implements UserService {

	@Autowired
	private ZyCommonService zyCommonService;
	@Autowired
	private SystemService systemService;
	
	public TSUser checkUserExits(TSUser user){
		return this.commonDao.getUserByUserIdAndUserNameExits(user);
	}

	public TSUser checkAppUserExits(TSUser user){
		return this.commonDao.getUserByUserNameAndPwd(user);
	}
	
	public TSUser checkUserExitsByPhone(TSUser user){
		return this.commonDao.getUserByUserIdAndPhoneExits(user);
	}
	
	public String getUserRole(TSUser user){
		return this.commonDao.getUserRole(user);
	}
	
	public void pwdInit(TSUser user,String newPwd) {
			this.commonDao.pwdInit(user,newPwd);
	}
	
	public int getUsersOfThisRole(String id) {
		Criteria criteria = getSession().createCriteria(TSRoleUser.class);
		criteria.add(Restrictions.eq("TSRole.id", id));
		int allCounts = ((Long) criteria.setProjection(
				Projections.rowCount()).uniqueResult()).intValue();
		return allCounts;
	}

	@Override
	public void doChangeAppuserMobilePhone(String mobilePhone) {
		TSUser user = ResourceUtil.getSessionUserName();
		user = super.getEntity(TSUser.class, user.getId());
		user.setMobilePhone(mobilePhone);
		super.saveOrUpdate(user);
		String userId = user.getId();
		
		List<TSRoleUser> roleUsers = systemService.findByProperty(TSRoleUser.class, "TSUser.id", userId);
		List<String> userRoleCodeList = new ArrayList<String>();
		for (TSRoleUser tsRoleUser : roleUsers) {
			userRoleCodeList.add(tsRoleUser.getTSRole().getRoleCode());
		}
		
		///修改用户关联的 联系人 或 工程师表的 手机号
		StringBuffer sql = new StringBuffer();
		sql.append(" SELECT ");
		sql.append(" 	ct.id AS ctId, eg.id AS egId, eg.name AS egName ");
		sql.append(" FROM ");
		sql.append(" 	t_s_base_user bu ");
		sql.append(" LEFT JOIN zy_contacts ct ON ct.base_id = bu.ID ");
		sql.append(" LEFT JOIN zy_engineer eg ON eg.ts_base_user_id = bu.ID ");
		sql.append(" WHERE bu.ID = '").append(userId).append("' ");
		List<Map<String, Object>> ctOrEgMapList = super.findForJdbc(sql.toString());
		if(null != ctOrEgMapList && ctOrEgMapList.size() > 0){
			boolean had = false;
			for (Map<String, Object> map : ctOrEgMapList) {
				//如果系统用户 关联了工程师 & 联系人。那么都修改手机号
				if(null != map.get("ctId") && StringUtil.isNotEmpty(map.get("ctId"))){
					ZyContactsEntity ct = super.get(ZyContactsEntity.class, map.get("ctId").toString());
					ct.setCellphone1(mobilePhone);
					super.saveOrUpdate(ct);
					had = true;
				}
				if(null != map.get("egId") && StringUtil.isNotEmpty(map.get("egId"))){
					ZyEngineerEntity eg = super.get(ZyEngineerEntity.class, map.get("egId").toString());
					eg.setCellphone(mobilePhone);
					super.saveOrUpdate(eg);
					had = true;
				}
			}
			if(had){
				try {
					//如果是工程师 ，区域工程师 给本公司的第三方商务 生成APP消息
					if(userRoleCodeList.contains(StaticValue.RULE_CODE_AREA_ENGINEER) || userRoleCodeList.contains(StaticValue.RULE_CODE_THIRDPARTY_ENGINEER)){
						String orgCode = zyCommonService.getUserRootTsDepartCode(user.getCurrentDepart()).getOrgCode();
						List<ZyContactsEntity> cts = zyCommonService.queryUsersByConditions(orgCode,StaticValue.DIC_BUS_SCOPE_INSPECTION,StaticValue.RULE_CODE_THIRDPARTY_HEADER,StaticValue.DIC_CONTACT_POSITION_TP_SERVER_BUSINESSR);
						if(null != cts && cts.size() > 0){
							//创建 APP消息
							CbsAppMessageEntity appMessage = new CbsAppMessageEntity();
							String content = "本公司的["+ user.getRealName() +"]修改手机号码为"+ mobilePhone +"，请知悉。";
							appMessage.setContent(content);
							appMessage.setSender(user.getId());
							appMessage.setReciver(cts.get(0).getTsBaseUser().getId());
							appMessage.setState(StaticValue.DIC_APP_MESSAGE_STATE_UNREAD);
							systemService.save(appMessage);
							systemService.addLog("新增APP消息,接受方:" + appMessage.getReciver() + ",内容:" + content, Globals.Log_Leavel_INFO, Globals.log_type_SEND_EMAIL);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				try {
					//给巴可第三方主管发送邮件
					List<TSUserOrg>  userOrgList = user.getUserOrgList();
					if(null != userOrgList && userOrgList.size() > 0){
						TSUserOrg userOrg = userOrgList.get(0);
						if(null != userOrg.getTsDepart()){
							TSDepart rootDepart = zyCommonService.getUserRootTsDepartCode(userOrg.getTsDepart());
							List<Map<String, Object>> barcoServerDirectorMapList = zyCommonService.queryUserNamesListByOrgCodeAndRoleCode(StaticValue.ORG_CODE_BARCO,StaticValue.RULE_CODE_BARCO_SERVER_DIRECTOR);
							if(null != barcoServerDirectorMapList && barcoServerDirectorMapList.size() > 0){
								Map<String, Object> paramMap = new HashMap<String, Object>();
								paramMap.put("companyName", rootDepart.getDepartname());
								paramMap.put("changerName", user.getRealName());
								paramMap.put("changePhone", mobilePhone);
								ZyEmailEntity email = new ZyEmailEntity();
								email.setEmailReceiver(barcoServerDirectorMapList.get(0).get("email").toString());
								email.setEmailSubject("工程师修改手机号");
								SendMailUtil.sendFtlMail(email, "mail_appChangeMobilePhoneToBarco.ftl", paramMap, systemService);
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void doAppChangeEmail(HttpServletRequest req, AjaxJson j) {
		String email = oConvertUtils.getString(req.getParameter("email"));
		if(!email.equals("")){
			TSUser user = ResourceUtil.getSessionUserName();
			user = systemService.getEntity(TSUser.class, user.getId());
			user.setEmail(email);
			systemService.saveOrUpdate(user);
			String userId = user.getId();
			///修改用户关联的 联系人 或 工程师表的 邮箱
			StringBuffer sql = new StringBuffer();
			sql.append(" SELECT ");
			sql.append(" 	ct.id AS ctId, eg.id AS egId ");
			sql.append(" FROM ");
			sql.append(" 	t_s_base_user bu ");
			sql.append(" LEFT JOIN zy_contacts ct ON ct.base_id = bu.ID ");
			sql.append(" LEFT JOIN zy_engineer eg ON eg.ts_base_user_id = bu.ID ");
			sql.append(" WHERE bu.ID = '").append(userId).append("' ");
			List<Map<String, Object>> ctOrEgMapList = super.findForJdbc(sql.toString());
			if(null != ctOrEgMapList && ctOrEgMapList.size() > 0){
				for (Map<String, Object> map : ctOrEgMapList) {
					//如果系统用户 关联了工程师 & 联系人。那么都修改邮箱
					if(null != map.get("ctId") && StringUtil.isNotEmpty(map.get("ctId"))){
						ZyContactsEntity ct = super.get(ZyContactsEntity.class, map.get("ctId").toString());
						ct.setEmail(email);
						super.saveOrUpdate(ct);
					}
					if(null != map.get("egId") && StringUtil.isNotEmpty(map.get("egId"))){
						ZyEngineerEntity eg = super.get(ZyEngineerEntity.class, map.get("egId").toString());
						eg.setEmail(email);
						super.saveOrUpdate(eg);
					}
				}
			}
		}else{
			j.setSuccess(false);
			j.setMsg("邮箱为空");
		}
	}

    @Override
    public int getUserCountOfThisRoleCode(String roleCode) {
        List rus = findHql("from TSRoleUser where TSRole.roleCode=?",roleCode);
        return rus.size();
    }

    @Override
    public boolean hasRole(String userName,String roleCode) {
        List<TSRoleUser> rus = findHql("from TSRoleUser where TSRole.roleCode=?",roleCode);
        for(TSRoleUser roleUser : rus){
            if(userName.equals(roleUser.getTSUser().getUserName())){
                return true;
            }
        }
        return false;
    }
    
    @Override
    public boolean hasRoles(String userName,String[] roleCodes) {
        List<TSRoleUser> rus = findHql("from TSRoleUser where TSUser.userName=?",userName);
        for(String roleCode : roleCodes){
        	for(TSRoleUser roleUser : rus){
	            if(null != roleCode && 
	            		roleCode.equals(roleUser.getTSRole().getRoleCode())){
	            	return true;
	            }
        	}
        }
        return false;
    }

    @Override
    public String assebleChainLogo(String bpCode) {
        String logo = "";
        //optimize
        List<TSType> types = findHql("from TSType where TSTypegroup.typegroupcode='"+StaticValue.DIC_CHAIN_REPORT+" 'and typecode like '%"+bpCode+"%'");
        if(types.size() > 0){
            switch(types.get(0).getTypename()){
                case "中影":
                    logo = "chain_zy_logo.jpg";
                    break;
                case "金逸":
                    logo = "chain_jy_logo.jpg";
                    break;
                case "大地":
                    logo = "chain_dadi_logo.jpg";
                    break;
                case "CGV":
                    logo = "chain_CGV_logo.jpg";
                    break;
                case "横店":
                    logo = "chain_hd_logo.jpg";
                    break;

            }
        }
        return logo;
    }

	/**
	 * 添加微信用户
	 * @param openId 微信openId
	 * @param realName 姓名
	 * @param userName 用户名
	 * @param phone 手机号码
	 * @param authLevel 注册权限等级
	 * @return
	 */
    public TSUser addWxUser(String openId, String realName, String userName, String phone, String authLevel,String headImg) {
    	TSUser user = new TSUser();
    	if(StringUtil.isEmpty(userName)){
			userName = PinyinUtil.getPinYin(realName);
		}
		user.setRealName(realName);
		List<TSUser> repeatUserList = systemService.findHql("from TSUser where userName = ?", userName);
		if (repeatUserList.size() > 0) {
			Integer num = repeatUserList.size() == 1 ? 1 : repeatUserList.size() + 1;
			userName = userName + num;
		}
		user.setUserName(userName);
		user.setPassword(PasswordUtil.encrypt(user.getUserName(), "123456", PasswordUtil.getStaticSalt()));
		user.setAppPassword(user.getPassword());
		user.setStatus(Globals.User_Normal);
		user.setActivitiSync((short) 0);
		user.setAuthenticationLevel(authLevel);
		user.setMobilePhone(phone);
		user.setUserKey("");
		user.setOpenId(openId);
		user.setWxHeadImgUrl(headImg);
		save(user);
		return user;
    }

    @Override
    public List<TSUser> getUserByMobilePhone(String mobilePhone) {
		List<TSUser> users = findHql("from TSUser where mobilePhone=?",mobilePhone);
        return users;
    }

}
